package xyz.thoughtset.viewer.executor.blocks.tool;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.model.ToolContext;
import org.springframework.ai.tool.ToolCallback;
import org.springframework.ai.tool.definition.ToolDefinition;
import org.springframework.ai.tool.metadata.ToolMetadata;
import xyz.thoughtset.viewer.executor.blocks.executor.BlockExecutorManager;

import java.util.Map;

@Slf4j
public record MCPServerBlockToolCallback(ToolDefinition toolDefinition,
                                         BlockExecutorManager blockExecutorManager,
                                         ObjectMapper objectMapper, String funId) implements ToolCallback {
//    private final ToolDefinition toolDefinition;
//    private final BlockExecutorManager blockExecutorManager;
//    private final ObjectMapper objectMapper;

    @Override
    public ToolDefinition getToolDefinition() {
        return toolDefinition;
    }

    @Override
    public ToolMetadata getToolMetadata() {
        return ToolCallback.super.getToolMetadata();
    }

    @Override
    public String call(String toolInput) {
        return call(toolInput,null);
    }

    @SneakyThrows
    @Override
    public String call(String toolInput, ToolContext toolContext) {
        Map paramMap = objectMapper.readValue(toolInput,Map.class);
        if (toolContext != null && toolContext.getContext() != null){
            paramMap.putAll(toolContext.getContext());
        }
        Object result = blockExecutorManager.execBlocks(funId,paramMap);
        log.info(objectMapper.writeValueAsString(result));
        return objectMapper.writeValueAsString(result);
    }
}
